﻿using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenAuth.App
{
    public class CheckViolationApp : BaseApp<InspectViolation>
    {
        public CheckViolationApp(IUnitWork unitWork, IRepository<InspectViolation> repository)
            : base(unitWork, repository)
        {
        }

        public void CheckViolation()
        {
            var plans = UnitWork.Find<InspectPlan>(u => u.Status == 1).ToList();
            List<string> planIds = plans.Select(u => u.Id).ToList();
            DateTime now = DateTime.Now;
            var schedules = UnitWork.Find<InspectSchedule>(u => u.EndTime < now
                && u.EndTime >= (now.AddMinutes(-20)) && planIds.Contains(u.InspectPlanId));
            DateTime today = DateTime.Today;
            var violationList = UnitWork.Find<InspectViolation>(u => u.CreateTime > today).Select(u=>u.InspectScheduleId).ToList();
            foreach (var item in schedules)
            {
                if (item.IsInspection)
                    continue;
                if (violationList.Contains(item.Id))
                    continue;
                var plan = plans.FirstOrDefault(u => u.Id == item.InspectPlanId);
                if (plan != null)
                    UnitWork.Add(new InspectViolation
                    {
                        InspectPlanId = item.InspectPlanId,
                        OrgId = plan.OrgId,
                        InspectScheduleId = item.Id,
                        Reason = "超时未点检",
                        Category = 0,
                        IsViolation = true,
                        Status = 0
                    });
            }
            UnitWork.Save();
        }
    }
}
